package com.zhw.goshopping.content.service;

import com.zhw.goshopping.common.pojo.GoShoppingResult;
import com.zhw.goshopping.common.utils.JsonUtils;
import com.zhw.goshopping.content.jedis.JedisClient;
import com.zhw.goshopping.dao.TbContentMapper;
import com.zhw.goshopping.pojo.TbContent;
import com.zhw.goshopping.pojo.TbContentExample;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * Create by zhaihongwei on 2018/3/24
 */
@Service
public class ContentServiceImpl implements ContentService{

    @Autowired
    private TbContentMapper contentMapper;

    @Autowired
    private JedisClient jedisClient;

    @Value("${INDEX_CONTENT}")
    private String INDEX_CONTENT;

    @Override
    public List<TbContent> getContentListByCid(long categoryId) {
        // 查询缓存
        // 添加缓存不能影响业务逻辑
        try {
            // 查询缓存，把json转换成list，返回
            String json = jedisClient.hget(INDEX_CONTENT,categoryId+"");
            if (StringUtils.isNotBlank(json)) {
                List<TbContent> list = JsonUtils.jsonToList(json,TbContent.class);
                return list;
            }
        }catch (Exception e) {
            e.printStackTrace();
        }

        // 缓存中没有命中，需要查询数据库
        TbContentExample example = new TbContentExample();
        TbContentExample.Criteria criteria = example.createCriteria();
        // 设置查询条件
        criteria.andCategoryIdEqualTo(categoryId);
        // 执行查询
        List<TbContent> list = contentMapper.selectByExample(example);

        // 把结果添加到缓存
        try {
            jedisClient.hset(INDEX_CONTENT,categoryId+ "", JsonUtils.objectToJson(list));
        }catch (Exception e) {
            e.printStackTrace();
        }

        // 返回结果
        return list;
    }

    @Override
    public GoShoppingResult addContent(TbContent tbContent) {
        // 补全pojo属性
        Date date = new Date();
        tbContent.setCreated(date);
        tbContent.setUpdated(date);
        // 插入到内容表
        contentMapper.insert(tbContent);
        //同步缓存
        //删除对应的缓存信息
        jedisClient.hdel(INDEX_CONTENT, tbContent.getCategoryId().toString());
        return GoShoppingResult.ok();
    }
}
